package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐服务提供者实现类
 *
 * @author zhengjd
 * @date 2020/4/1 13:04
 */
@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String outputpath;   //获取输出静态页面路径

    /**
     * 分页查询套餐列表
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Setmeal> setmeals = setmealDao.findPage(queryPageBean.getQueryString());
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmeals);
        return new PageResult(pageInfo.getTotal(), setmeals);
    }

    /**
     * 根据套餐id查询检查组的id集合
     */
    @Override
    public List<Integer> findCheckGroupIdBySetmeal(Integer id) {
        return setmealDao.findCheckGroupIdBySetmeal(id);
    }

    /**
     * 添加套餐
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        addSetmealIdAndCheckGroupId(setmeal.getId(), checkgroupIds);
        //生成静态页面
        generateMobileStaticHtml();

    }

    /**
     * 添加套餐和检查组的关系
     */
    @Override
    public void addSetmealIdAndCheckGroupId(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("checkGroup_id", checkgroupId);
                map.put("setmeal_id", setmealId);
                setmealDao.addCheckgroupIds(map);
            }
        }
    }

    /**
     * 根据id查询套餐
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    /**
     * 编辑套餐
     */
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //根据传递的套餐id查询原数据库的img数据
        Setmeal setmeal_db = findById(setmeal.getId());
        String dbImg = setmeal_db.getImg();
        //进行判断两者是否相同
        if (setmeal.getImg() != null && !setmeal.getImg().equals(dbImg)) {
            //删除七牛云和Redis上的图片资源
            deleteImgFromQiniuAndRedis(dbImg);
        }
        setmealDao.edit(setmeal);
        //删除套餐和检查组的关系数据
        setmealDao.delRelShip(setmeal.getId());
        addSetmealIdAndCheckGroupId(setmeal.getId(), checkgroupIds);

        //编辑时生成静态套餐列表页面和编辑的套餐详情静态页面
        generateMobileSetmealListHtml(getSetmeal());
        //生成单个套餐详情静态页面
        generateMobileSetmealDetailHtml(setmeal.getId());
        //如果关联检查组为空时，则删除套餐详情静态页面
        if (checkgroupIds == null || checkgroupIds.length == 0){
            deleteMobileStaticHtml(setmeal.getId());
        }


    }


    /**
     * 删除套餐
     */
    @Override
    public void delete(Integer id) {
        Setmeal setmeal_db = findById(id);
        int c1 = setmealDao.CheckGroupIdsBySetMealId(id);
        if (c1 > 0) {
            throw new RuntimeException(MessageConstant.ERROR1_SETMEAL_DELETE);
        }
        int c2 = setmealDao.OrderBySetMealId(id);
        if (c2 > 0) {
            throw new RuntimeException(MessageConstant.ERROR2_SETMEAL_DELETE);
        }
        setmealDao.delete(id);

        String dbImg = setmeal_db.getImg();
        if (dbImg != null && !"".equals(dbImg)) {
            //删除七牛云和Redis上的图片资源
            deleteImgFromQiniuAndRedis(dbImg);
        }

        //删除后重新生成静态页面
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(getSetmeal());
        deleteMobileStaticHtml(id);
    }
    /**
     * 删除套餐详情静态页面
     */
    public void deleteMobileStaticHtml(Integer id){
        //删除指定的套餐详情列表
        File file = new File(outputpath + "/" + "m_setmeal_detail_" + id + ".html");
        if (file.exists()){
            file.delete();
        }
    }

    /**
     * 删除七牛云和Redis上的图片资源
     *
     * @param dbImg
     */
    public void deleteImgFromQiniuAndRedis(String dbImg) {
        //从七牛云将图片数据删除
        QiniuUtils.deleteFileFromQiniu(dbImg);
        Jedis jedis = jedisPool.getResource();
        //从Redis中将图片名称删除
        jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES, dbImg);
        jedis.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, dbImg);
        jedis.close();
    }

    /**
     * 获取套餐列表
     *
     * @return
     */
    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.getSetmeal();
    }


    /**
     * 生成静态页面
     */
    public void generateMobileStaticHtml() {
        //准备模板文件中需要的数据
        List<Setmeal> setmealList = this.getSetmeal();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    /**
     * 生成套餐列表静态页面
     *
     * @param setmealList
     */
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);

    }

    /**
     * 生成套餐详情静态页面（多个）
     *
     * @param setmealList
     */
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        if (setmealList != null && setmealList.size() > 0) {
            for (Setmeal setmeal : setmealList) {
                generateMobileSetmealDetailHtml(setmeal.getId());
                }
            }

    }

    /**
     * 生成套餐详情静态页面（单个）
     */
    public void generateMobileSetmealDetailHtml(Integer setmealId) {
        Setmeal newSetmeal = this.findById(setmealId);
        if (newSetmeal.getCheckGroups() != null && newSetmeal.getCheckGroups().size() > 0) {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal", newSetmeal);
            this.generateHtml("mobile_setmeal_detail.ftl", "m_setmeal_detail_" + setmealId + ".html", dataMap);
        }

    }


    /**
     * 读取模板和输出数据
     *
     * @param templateName 模板文件名称
     * @param htmlPageName 生成静态页面的文件名
     * @param dataMap      模板数据
     */
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        //获取配置类
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Writer out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File docFile = new File(outputpath + "/" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
